package com.york.jobmew.subject.domain.config;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义名称的线程工厂
 * 实现ThreadFactory接口，自定义线程池中的名字前缀，模仿即可
 */
public class CustomNameThreadFactory implements ThreadFactory {

    /**
     * 线程安全的，cas操作保证，线程池号
     */
    private static final AtomicInteger poolNumber = new AtomicInteger(1);

    /**
     * 分组
     */
    private final ThreadGroup group;

    /**
     * 线程号
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);

    /**
     * 名称前缀
     */
    private final String namePrefix;

    CustomNameThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        if (StringUtils.isBlank(name)) {
            name = "pool";
        }
        namePrefix = name + "-" +
                poolNumber.getAndIncrement() +
                "-thread-";
    }

    /**
     * 由线程池创建的线程规则
     *
     * @param r a runnable to be executed by new thread instance
     * @return
     */
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        // 必须在创建前设置是否是Daemon守护线程，否则开启以后的设置时无效的
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }

}
